//
//  ECOrderCheckPendingViewController.m
//  ECERP.CRM
//
//  Created by 刘思麟 on 2018/10/28.
//  Copyright © 2018年 Mac. All rights reserved.
//

#import "ECOrderBaseViewController.h"
#import "ECOrderChekPendingListTableViewCell.h"
#import "ECOrderModel.h"
#import "ECOrderDateSegePicker.h"

@interface ECSubTableView:UITableView

@end

@interface ECOrderBaseViewController ()<UITableViewDelegate,UITableViewDataSource> {
    ECOrderDateSegePicker * datePicker;
}

@property (nonatomic,strong) ECSubTableView * tableView;

@property (nonatomic,strong) NSMutableArray<ECOrderModel*> * dataArr;

@property (nonatomic,assign) NSInteger cuPage;

@property (nonatomic,strong) UIView * searchToolView;

@property (nonatomic,strong) UISearchBar * searchBar;

@property (nonatomic,strong) UIButton * searchSelectBT;

@end

@implementation ECSubTableView

- (void)layoutSubviews {
    [super layoutSubviews];
    for (UIView * subView in self.subviews) {
        if ([subView isKindOfClass:NSClassFromString(@"UISwipeActionPullView")]) {
            for (int index =0 ;index<subView.subviews.count;index++) {
                UIView * childView = subView.subviews[index];
                for (UIView *scV in childView.subviews) {
                    if ([scV isKindOfClass:NSClassFromString(@"UIButtonLabel")]) {
//                        if (index == 0) {
//                            ((UILabel*)scV).textColor = ECCOLOR(0x41d95a);
//                        }
                        ((UILabel*)scV).font = ECFONT(16 * PX_RELATIVE375);
                    }
                }
            }
        }
    }
}

@end

@implementation ECOrderBaseViewController

- (void)viewDidLoad {
    self.cuPage = 1;
//    self.navigationItem.title = @"待审核订单";
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"search_icon"] style:UIBarButtonItemStylePlain target:self action:nil];
    [super viewDidLoad];
    [self requestData:self.cuPage];
    // Do any additional setup after loading the view.
}

- (void)loadSubView {
    WS(weakSelf, self);
    [self.view addSubview:self.searchToolView];
    [self.searchToolView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(0);
        make.height.mas_equalTo(54);
    }];
    [self.searchToolView addSubview:self.searchSelectBT];
    [self.searchSelectBT mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(weakSelf.searchToolView);
        make.right.mas_equalTo(weakSelf.searchToolView).mas_offset(-10);
        make.height.with.mas_equalTo(24);
    }];
    
    self.searchBar.layer.cornerRadius = 16;
    self.searchBar.clipsToBounds = YES;
    self.searchBar.layer.borderWidth = 1;
    self.searchBar.layer.borderColor = ECCOLOR(0xcccccc).CGColor;
    [self.searchToolView addSubview:self.searchBar];
    [self.searchBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(weakSelf.searchToolView).mas_offset(12*PX_RELATIVE375);
        make.centerY.mas_equalTo(weakSelf.searchToolView);
        make.height.mas_equalTo(32);
        make.right.mas_equalTo(weakSelf.searchSelectBT.mas_left).mas_offset(-5);
    }];
    
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.top.mas_equalTo(weakSelf.searchToolView.mas_bottom);
        if (@available(iOS 11.0,*)) {
            make.bottom.mas_equalTo(weakSelf.view.mas_safeAreaLayoutGuideBottom);
        }
    }];
}
#pragma mark httpRequest
- (void)requestData:(NSInteger)page {
    NSMutableDictionary * paraDic = @{@"page":@(page),@"limit":@(20),@"billState":self.billState}.mutableCopy;
    [GLHTTPTool getWithURL:Api_OrderList params:paraDic success:^(id json) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        if ([json[@"code"] integerValue] == 0) {
            NSArray * daraAr = [NSArray modelArrayWithClass:[ECOrderModel class] json:json[@"data"]];
            if (self.cuPage <= 1) {
                self.dataArr = daraAr;
            }else {
                [self.dataArr addObjectsFromArray:daraAr];
                [self.tableView reloadData];
            }
            if (daraAr.count >= 20) {
                self.cuPage = page + 1;
            }else {
                self.cuPage = page;
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
        }else{
            self.cuPage = page;
            [MBProgressHUD showMessage:json[@"msg"] toView:self.view];
        }
    } failure:^(NSError *error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        self.cuPage = page;
    }];
}

- (void)requestForDeleteOrderWithModel:(ECOrderModel*)model{
    NSString * ID = model.Id;
    __weak typeof(self) weakSelf = self;
    __block typeof(model) blockModel = model;
    [GLHTTPTool postWithURL:Api_OrderDelete params:@{@"id":ID} success:^(id json) {
        if ([json[@"code"] integerValue] == 0) {
            NSIndexPath * indexPath = [NSIndexPath indexPathForRow:[weakSelf.dataArr indexOfObject:blockModel] inSection:0];
            [weakSelf.tableView beginUpdates];
            [weakSelf.tableView reloadRowAtIndexPath:indexPath withRowAnimation:UITableViewRowAnimationNone];
            [weakSelf.tableView endUpdates];
        }
    } failure:^(NSError *error) {
        
    }];
}

- (void)requestForCheckBatchWithModel:(ECOrderModel*)model{
    NSString * ID = model.Id;
    __weak typeof(self) weakSelf = self;
    __block typeof(model) blockModel = model;
    [GLHTTPTool postWithURL:Api_OrderCheckBatch params:@{@"ids":@[ID]} success:^(id json) {
        if ([json[@"code"] integerValue] == 0) {
            NSIndexPath * indexPath = [NSIndexPath indexPathForRow:[weakSelf.dataArr indexOfObject:blockModel] inSection:0];
            [weakSelf.tableView beginUpdates];
            [weakSelf.tableView reloadRowAtIndexPath:indexPath withRowAnimation:UITableViewRowAnimationNone];
            [weakSelf.tableView endUpdates];
        }
    } failure:^(NSError *error) {
        
    }];
}

- (void)setDataArr:(NSMutableArray *)dataArr {
    _dataArr = dataArr;
    if (_dataArr && _dataArr.count > 0) {
        [self.tableView reloadData];
        self.dataState = ECBaseDataStateData;
    }else {
        self.dataState = ECBaseDataStateNOData;
    }
}

- (void)doFilter:(UIButton*)sender {
    if(!datePicker){
        datePicker= [ECOrderDateSegePicker new];
    }
    datePicker.makeSureBlock = ^(NSDate * _Nonnull start, NSDate * _Nonnull end) {
        NSLog(@"ddd");
    };
    [datePicker show];
}

#pragma mark -UITableViewDelegate,UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 100 * PX_RELATIVE375;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ECOrderModel * model = self.dataArr[indexPath.row];
    ECOrderChekPendingListTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.codeLB.text = model.orderCode;
    cell.nameLB.text = model.customerName;
    cell.sumLB.text = [NSString stringWithFormat:@"预定：%.2f",[model.orderAmount floatValue]];
    switch ([model.billState integerValue]) {
        case -1:{
            cell.iconImgV.image = [UIImage imageNamed:@"order_icon_作废"];
        }
            break;
        case 0:
            {
                cell.iconImgV.image = [UIImage imageNamed:@"order_icon_待审核"];
            }
            break;
        case 1:{
            cell.iconImgV.image = [UIImage imageNamed:@"order_icon_待发货"];
        }
            break;
        case 2:{
            cell.iconImgV.image = [UIImage imageNamed:@"order_icon_待复核"];
            cell.sumChildLB.text = [NSString stringWithFormat:@"实发：%.2f",[model.sendOutAmount floatValue]];
        }
            break;
        case 3:{
            cell.iconImgV.image = [UIImage imageNamed:@"order_icon_待收款"];
            cell.sumLB.text = [NSString stringWithFormat:@"实发：%.2f",[model.sendOutAmount floatValue]];
            cell.sumChildLB.text = [NSString stringWithFormat:@"复核：%.2f",[model.affireAmount floatValue]];
        }
            break;
        case 4:{
            cell.iconImgV.image = [UIImage imageNamed:@"order_icon_已收款"];
        }
            break;
        default:
            break;
    }
    cell.userLB.text = [NSString stringWithFormat:@"创建人：%@",model.createBy];
    if (model.createOn && model.createOn.length > 0) {
        cell.dateLB.text = [model.createOn componentsSeparatedByString:@" "].firstObject;
    }
    return cell;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleNone;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    __weak typeof(self) weakSelf = self;
    ECOrderModel * model = self.dataArr[indexPath.row];
    switch ([model.billState integerValue]) {
        case 0:
            {
                UITableViewRowAction * action1 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"作废" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
                    [weakSelf requestForDeleteOrderWithModel:model];
                }];
                action1.backgroundColor = ECCOLOR(0xFF3C32);
                UITableViewRowAction * action2 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"审核" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
                    [weakSelf requestForCheckBatchWithModel:model];
                }];
                action2.backgroundColor = ECCOLOR(0x00A61E);
                return @[action1,action2];
            }
            break;
        case 1:{
            UITableViewRowAction * action1 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"发货" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
                [weakSelf requestForDeleteOrderWithModel:model];
            }];
            action1.backgroundColor = ECCOLOR(0x00A61E);
            return @[action1];
        }
            break;
        case 2:{
            UITableViewRowAction * action1 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"驳回" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
                [weakSelf requestForDeleteOrderWithModel:model];
            }];
            action1.backgroundColor = ECCOLOR(0xFF3C32);
            UITableViewRowAction * action2 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"复核" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
                [weakSelf requestForCheckBatchWithModel:model];
            }];
            action2.backgroundColor = ECCOLOR(0x00A61E);
            return @[action1,action2];
        }
            break;
        case 3:{
            UITableViewRowAction * action1 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"驳回" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
                [weakSelf requestForDeleteOrderWithModel:model];
            }];
            action1.backgroundColor = ECCOLOR(0xFF3C32);
            UITableViewRowAction * action2 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"结算" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
                [weakSelf requestForCheckBatchWithModel:model];
            }];
            action2.backgroundColor = ECCOLOR(0x00A61E);
            return @[action1,action2];
        }
            break;
        default:
            break;
    }
    return nil;
}

#pragma mark LazyLoad

- (ECSubTableView *)tableView {
    if (!_tableView) {
        __weak typeof(self) weakSelf = self;
        _tableView = [ECSubTableView new];
        _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0.00000001)];
        _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0.00000001)];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.sectionHeaderHeight = 12 * PX_RELATIVE375;
        _tableView.sectionFooterHeight = 0.00001 * PX_RELATIVE375;
        [_tableView registerClass:[ECOrderChekPendingListTableViewCell class] forCellReuseIdentifier:@"cell"];
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [weakSelf requestData:1];
        }];
        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            [weakSelf requestData:self.cuPage];
        }];
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}

- (UIView *)searchToolView {
    if (!_searchToolView) {
        _searchToolView = [UIView new];
    }
    return _searchToolView;
}

- (UISearchBar *)searchBar {
    if (!_searchBar) {
        _searchBar = [UISearchBar new];
        [_searchBar setImage:[UIImage imageNamed:@"search_member"] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
        _searchBar.placeholder = @"客户名称/编号/联系人/手机号码";
        [_searchBar setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor]]];
        [_searchBar setPositionAdjustment:UIOffsetMake(-6, 0) forSearchBarIcon:UISearchBarIconSearch];
        for (UIView * v in _searchBar.subviews.firstObject.subviews) {
            if ([v isKindOfClass:NSClassFromString(@"UISearchBarTextField")]) {
                UITextField * tf = (UITextField*)v;
                tf.font = ECFONT(14);
            }
        }
    }
    return _searchBar;
}

- (UIButton *)searchSelectBT {
    if (!_searchSelectBT) {
        _searchSelectBT = [UIButton buttonWithType:UIButtonTypeCustom];
        [_searchSelectBT setBackgroundImage:[UIImage imageNamed:@"select_member"] forState:UIControlStateNormal];
        [_searchSelectBT setBackgroundImage:[UIImage imageNamed:@"select_member_on"] forState:UIControlStateSelected];
        [_searchSelectBT addTarget:self action:@selector(doFilter:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _searchSelectBT;
}

@end
